﻿
var dialogID, rowCount;  // dialogID窗口id  rowCount 数据库记录数
//（_page_url,page_url)分页处理地址 (_get_url , get_url)获取数据地址 （_Array_id,Array_id）数据表字段id   
//(_container,container) 容器id   (_row,row)行   (_column,column)列  (_Array_title,Array_title)表头标题  
//(_table,table)修改的表名  (curr_num,num)当前页   datacount纪录总数
var _page_url, _get_url, _Array_id, _container, _row, _column, _Array_title, _table, curr_num = 1, datacount = 0;
var myTable;
//全部删除  deleteCount 统计删除数据的记录个数   
var deleteCount = 0;
//获取数据
//url 处理地址   Array_id数据表id    container 容器id   row行    column列  Array_title表头标题  table修改的表名  num当前页
function get(url, Array_id, container, row, column, Array_title, table, num) {
    var tmp = Math.random().toString();
    var select_row = parseInt($("#select_row").val()) ? parseInt($("#select_row").val()) : 10;
    var sql;
    if (num == 1) {
        sql = "select * from " + table + " order by time DESC" + " limit 0," + num * select_row;
    }
    else { sql = "select * from " + table + " order by time DESC" + " limit " + (num - 1) * select_row + "," + select_row; }
    //var test = { user_name: "objVal['user_name']", user_pwd: "objVal['user_pwd]", add_time: "objVal['add_time']" }
    //test["user_name"]; 常量
    $.ajax({
        type: 'POST',
        url: url + tmp,
        data: "sql=" + sql + "&curr=" + num,
        dataType: 'json',
        cache: false,
        beforeSend: function () {
            dialogID = layer.load(2, { shade: [0.1, '#fff'] });
        },
        success: function (data, textStatus) {
            layer.close(dialogID);
            var jsonData = eval(data);
            var Array_item = [];
            rowCount = jsonData.length;
            //create(container, row, column, Array_title, table);
            var _row = row;
            $("#" + container).empty();
            var c = 0;
            $("#" + container).append('<div id="dynamic-table_wrapper" class="dataTables_wrapper"></div>');
            $("#dynamic-table_wrapper").append('<table id="dynamic-table" class="table table-striped table-bordered table-hover"></table>')
            $("#dynamic-table").append("<thead id='title'></thead>")
            $("#title").append("<tr id='line'></tr>");
            for (c; c < column; c++) {
                if (c == 0) { $("#line").append("<th class='center'><lable class='pos-rel'><input type='checkbox' id='checkall' class='ace' /><span class='lbl'></span></lable></th>"); }
                else { $("#line").append("<th>" + Array_title[c - 1] + "</th>"); }
            }
            $("#dynamic-table").append("<tbody id='cont'></tbody")
           
            original_row = -1;//纪录点击的行 -1 为归位。
            if (rowCount < row) { row = rowCount; } else if (rowCount > row || row > _row) { row = _row; }
            $.each(jsonData, function (index, objVal) { //遍历对象数组，index是数组的索引号，objVal是遍历的一个对象。objVal["属性"]可取到对应的属性值。 
                $.each(Array_id, function (idx, val) {
                    Array_item.push(objVal[val]);
                });
                $("#cont").append("<tr id=r-" + index + "></tr>");
                var j = 0;
                for (j; j < column; j++) {
                    if (j == 0) {
                        $("#r-" + index).append("<td id='r-" + index + "-" + j + "' class='center'><label class='pos-rel'><input type='checkbox' class='ace' id=del-" + index + " Dataid=" + Array_id[0] + " Datavalue=" + Array_item[0] + " /><span class='lbl'></span><lable></td>");
                    }
                    else {
                        if (j == (column - 1)) {

                            $("#r-" + index).append("<td><div class='hidden-sm hidden-xs btn-group'><button title='编辑' Datavalue=" + Array_item[0] + " Dataid=" + Array_id[0] + " id='r-" + index + "-" + j + "' class='btn btn-xs btn-success' onclick=button_state('r-" + index + "-" + j + "','r-" + index + "-" + (j + 1) + "','r-" + index + "-" + (j + 2) + "','r-" + index + "-" + (j + 3) + "','" + index + "','" + j + "','edit');><i class='ace-icon fa fa-check bigger-120'></i></button>&nbsp;"
                            + "<button title='更新'Datavalue=" + Array_item[0] + " Dataid=" + Array_id[0] + " id='r-" + index + "-" + (j + 1) + "' class='btn btn-xs btn-info' onclick=button_state('r-" + index + "-" + j + "','r-" + index + "-" + (j + 1) + "','r-" + index + "-" + (j + 2) + "','r-" + index + "-" + (j + 3) + "','" + index + "','" + j + "','update','" + table + "');  style='display:none;'><i class='ace-icon fa fa-pencil bigger-120'></i></button>&nbsp;"
                            + "<button title='取消'Datavalue=" + Array_item[0] + " Dataid=" + Array_id[0] + " id='r-" + index + "-" + (j + 2) + "' class='btn btn-xs btn-purple'  onclick=button_state('r-" + index + "-" + j + "','r-" + index + "-" + (j + 1) + "','r-" + index + "-" + (j + 2) + "','r-" + index + "-" + (j + 3) + "','" + index + "','" + j + "','cancel');  style='display:none;'><i class='ace-icon fa fa-reply bigger-120'></i></button>&nbsp;"
                            + "<button title='删除'Datavalue=" + Array_item[0] + " Dataid=" + Array_id[0] + " id='r-" + index + "-" + (j + 3) + "' class='btn btn-xs btn-danger'  onclick=button_state('r-" + index + "-" + j + "','r-" + index + "-" + (j + 1) + "','r-" + index + "-" + (j + 2) + "','r-" + index + "-" + (j + 3) + "','" + index + "','" + j + "','delete','" + table + "');><i class='ace-icon fa fa-trash-o bigger-120'></i></button>&nbsp;"
                            + "<button title='生成' id='r-" + index + "-" + (j + 4) + "' class='btn btn-xs btn-warning' onclick=''><i class='ace-icon fa fa-flag bigger-120'></i></button></div></td>");
                        }
                        else {
                            $("#r-" + index).append("<td id='r-" + index + "-" + j + "'Dataid=" + Array_id[j] + ">" + Array_item[j] + "</td>")
                        }
                    }
                }
                $("#checkall").attr("Dataid", Array_id[0]);//主键

                //var row_count = $("#cont tr").length;
                //var column_count = $("#r-" + index + " td").length;

                //$("#checkall").attr("Dataid", Array_id[0]);//主键
                //var m = 0;
                ////列 
                //for (m; m < column_count; m++) {
                //    if (m == 0) {
                //        $("#del-" + index).attr("Datavalue", Array_item[0]);//主键
                //        $("#del-" + index).attr("Dataid", Array_id[0]);//主键
                //    } else {
                //        if (m >= column_count) {
                //            $("#r-" + index + "-" + m).attr("Datavalue", Array_item[0]);//主键
                //            $("#r-" + index + "-" + m).attr("Dataid", Array_id[0]);//主键ID
                //        }
                //        else {

                //            $("#r-" + index + "-" + m).html(Array_item[m]);
                //            $("#r-" + index + "-" + m).attr("Dataid", Array_id[m]);
                //        }
                //    }
                //}
                Array_item = [];
            });
            
             myTable = $('#dynamic-table').dataTable({

                "bLengthChange": false,
                "bInfo": false,
                "bAutoWidth": false,
                "paging": false,
                "select": {
                    style: 'multi'
                }
             });
             ResetTable();
            
            //$('#dynamic-table tbody').on('click', 'tr', function () {
            //    console.log($(this.cells[0]).find("input").attr("checked"));
            //    if (!$(this.cells[0]).find("input").attr("checked")) {
            //        console.log("选中");
            //        $(this.cells[0]).find("input").attr("checked", "true");
            //    } else { console.log("未选中"); $(this.cells[0]).find("input").removeAttr("checked"); }
            //});
        },
        error: function (xhr) {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                console.log(xhr);
                this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);

                return;
            }
            //layer.close(dialogID);
            //layer.msg('加载失败', { icon: 1, time: 2000 });
            return;
        },

    });
}



//绘制表格
//container 容器id   row行    column列  Array_title表头标题  table修改的表名
function create(container, row, column, Array_title, table) {
    

    //$("#itemContainer li").hover(
    //               function () { $(this).addClass("hover"); },
    //               function () { $(this).removeClass("hover"); }
    // );
    //$("#checkall").click(function () {
    //    for (var i = 0; i < $("#cont tr").length; i++) {

    //        if ($("#checkall").is(":checked")) {
    //            $("#del-" + i).prop("checked", true);  //全选
    //        }
    //        else {
    //            $("#del-" + i).prop("checked", false); //取消全选 
    //        }
    //    }
    //});

}



//数据库操作
function execute(sql) {
    return $.ajax({                                                  //调用jquery的ajax方法   
        type: "POST",                                      //设置ajax方法提交数据的形式   
        url: "handler/ExecuteHandler.ashx",                                       //把数据提交到ashx  
        data: "sql=" + sql,     //输入框writer中的值作为提交的数据 
        beforeSend: function () {
            
        },
        success: function (msg) {                  //提交成功后的回调，msg变量是输出的内容。      
            //如果有必要，可以把msg变量的值显示到某个DIV元素中 
            layer.msg('处理成功', { icon: 1 ,time:2000});
            JsonData = {};
            return true;
        },
        error: function (xhr) {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                console.log(xhr);
                this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                return false;
            }
            layer.msg('处理失败', { icon: 2, time: 2000 });
            return false;
        },
    });
}



//添加或者修改json数据  row 当前行id   name  json属性  value json值
//var employees = [
//{ "firstName": "Bill", "lastName": "Gates" },
//{ "firstName": "George", "lastName": "Bush" },
//{ "firstName": "Thomas", "lastName": "Carter" }
//];
var JsonData = {}, singleA = 0;
function setJson(row, name, value) {
    if (singleA != row && singleA > 0) {
        // 添加 或 修改
        JsonData = {};
        JsonData[name] = value;
        singleA = row;
    }
    else {
        // 添加 或 修改
        JsonData[name] = value;
        singleA = row;
    }
    console.log(JsonData);
}

//按钮状态   edit_button 编辑按钮 update_button 更新按钮 cancel_button 取消按钮 del_button 删除按钮 row 当前行 column 当前列 type 当前按钮类型
var original_row = -1;  //-1为第一点击 //纪录点击的行 -1 为归位。
function button_state(edit_button, update_button, cancel_button, del_button, row, column, type, tableid) {
    var row_count = $("#cont tr").length;
    var a = 1, b = 1, c = 1, r = 0;
    switch (type) {
        case "edit":
            if (document.getElementById("r-" + row + "-1").innerHTML != "&nbsp;") {//数据是否为空

                $("#" + edit_button + "").css("display", "none");
                $("#" + del_button + "").css("display", "none");
                $("#" + update_button + "").css("display", "");
                $("#" + cancel_button + "").css("display", "");
                for (c; c < column; c++) {
                    if ($("#r-" + row + "-" + c + "").attr("Dataid") != "time") {//时间字段不需要编辑
                        var value = $("#r-" + row + "-" + c + "").html();
                        $("#r-" + row + "-" + c + "").empty();
                        $("#r-" + row + "-" + c + "").attr("Datavalue", value);
                        $("#r-" + row + "-" + c + "").append("<input type='text' onchange=setJson('" + row + "','" + $("#r-" + row + "-" + c + "").attr("Dataid") + "',this.value) style='width:90%;' value='" + $("#r-" + row + "-" + c + "").attr("Datavalue") + "'/>");
                    } else { break;}
                }

                if (original_row != row) {
                    for (a; a < column; a++) {
                        if (a != row) {
                            $("#r-" + original_row + "-" + column + "").css("display", "");
                            $("#r-" + original_row + "-" + (Number(column) + 1) + "").css("display", "none");
                            $("#r-" + original_row + "-" + (Number(column) + 2) + "").css("display", "none");
                            $("#r-" + original_row + "-" + (Number(column) + 3) + "").css("display", "");
                        }
                    }
                    for (b; b < column; b++) {
                        if ($("#r-" + row + "-" + b + "").attr("Dataid") != "time") {//时间字段不需要编辑
                            $("#r-" + original_row + "-" + b + "").empty();
                            $("#r-" + original_row + "-" + b + "").append($("#r-" + original_row + "-" + b + "").attr("Datavalue"));
                        } else { break; }
                    }
                    //纪录当前行
                    original_row = row;
                }
            }
            else { layer.msg('无数据', { icon: 2 ,time:2000});}
            break;
        case "cancel":
            
            for (r; r < row_count; r++) {
                $("#r-" + r + "-" + column + "").css("display", "");
                $("#r-" + r + "-" + (Number(column) + 1) + "").css("display", "none");
                $("#r-" + r + "-" + (Number(column) + 2) + "").css("display", "none");
                $("#r-" + r + "-" + (Number(column) + 3) + "").css("display", "");
            }
            for (c; c < column; c++) {
                if ($("#r-" + row + "-" + c + "").attr("Dataid") != "time") {//时间字段不需要编辑
                    $("#r-" + row + "-" + c + "").empty();
                    $("#r-" + row + "-" + c + "").append($("#r-" + row + "-" + c + "").attr("Datavalue"));
                } else { break; }
            }
            break;
        case "update":
            //数据库操作
            var sqlstring = null;
            $.each(JsonData, function (idx, val) {//迭代jsondate 为空不执行。
                sqlstring = "UPDATE " + tableid + " SET";
                $.each(JsonData, function (name, value) {
                    sqlstring = sqlstring + " " + name + "='" + value + "',";
                }); 
            });
            if (sqlstring != null) {
                sqlstring = sqlstring.substring(0, sqlstring.length - 1) + " WHERE " + $("#del-" + row).attr("Dataid") + " ='" + $("#del-" + row).attr("Datavalue") + "'";
                if (execute(sqlstring)) {
                    $("#" + edit_button + "").css("display", "");
                    $("#" + del_button + "").css("display", "");
                    $("#" + update_button + "").css("display", "none");
                    $("#" + cancel_button + "").css("display", "none");
                    for (r; r < row_count; r++) {
                        $("#r-" + r + "-" + column + "").css("display", "");
                        $("#r-" + r + "-" + (Number(column) + 1) + "").css("display", "none");
                        $("#r-" + r + "-" + (Number(column) + 2) + "").css("display", "none");
                        $("#r-" + r + "-" + (Number(column) + 3) + "").css("display", "");
                    }
                    for (c; c < column; c++) {
                        if ($("#r-" + row + "-" + c + "").attr("Dataid") != "time") {//时间字段不需要编辑
                            var value = $("#r-" + row + "-" + c + " input").val();
                            $("#r-" + row + "-" + c).attr("Datavalue", value);
                            $("#r-" + row + "-" + c + " input").remove();
                            $("#r-" + row + "-" + c + "").append(value);
                        } else { break; }
                    }
                }
            }
            else {
                $("#" + edit_button + "").css("display", "");
                $("#" + del_button + "").css("display", "");
                $("#" + update_button + "").css("display", "none");
                $("#" + cancel_button + "").css("display", "none");
                for (r; r < row_count; r++) {
                    $("#r-" + r + "-" + column + "").css("display", "");
                    $("#r-" + r + "-" + (Number(column) + 1) + "").css("display", "none");
                    $("#r-" + r + "-" + (Number(column) + 2) + "").css("display", "none");
                    $("#r-" + r + "-" + (Number(column) + 3) + "").css("display", "");
                }
                for (c; c < column; c++) {
                    if ($("#r-" + row + "-" + c + "").attr("Dataid") != "time") {//时间字段不需要编辑
                        var value = $("#r-" + row + "-" + c + " input").val();
                        $("#r-" + row + "-" + c).attr("Datavalue", value);
                        $("#r-" + row + "-" + c + " input").remove();
                        $("#r-" + row + "-" + c + "").append(value);
                    } else { break; }
                }
                layer.msg('数据没有变动', { icon: 4, time: 2000 });
            }
            break;
        case "delete":
            if (document.getElementById("r-" + row + "-1").innerHTML != "&nbsp;") {//数据是否为空
                //询问框
                layer.confirm('您是否要删除？', {
                    btn: ['是的', '算了'] //按钮
                }, function () {
                    var sqlstring = "delete from " + tableid + " WHERE " + $("#del-" + row).attr("Dataid") + " ='" + $("#del-" + row).attr("Datavalue") + "'";
                    
                    if (execute(sqlstring)) {
                        $("#r-" + row).remove();
                        row_count = $("#cont tr").length;
                        deleteCount = deleteCount + 1;
                        //单独删除数据后 如果执行分页
                        if (row_count == 0) { 
                        curr_num = (parseInt(curr_num) - 1) <= 0 ? 1 : (parseInt(curr_num) - 1);
                        var current = Math.ceil((parseInt(datacount) - parseInt(deleteCount)) / $("#select_row").val()) == 0 ? 1 : Math.ceil((parseInt(datacount) - parseInt(deleteCount)) / $("#select_row").val());
                        $.jqPaginator('.pagination', {
                            totalPages: parseInt(current),
                            visiblePages: parseInt($("#select_row").val()),
                            //currentPage: parseInt(curr_num) - 1 == 0 ? curr_num = 1 : parseInt(curr_num) - 1,
                            currentPage:curr_num,
                            onPageChange: function (num, type) {
                                curr_num = num;
                                //page("handler/PageHandler.ashx?t=", "handler/GetHandler.ashx?t=", Array_id, container, row, column, Array_title, table);
                                get(_get_url, _Array_id, _container, _row, _column, _Array_title, _table, curr_num);
                            }
                        });
                        }
                    };
                    if (original_row != row) {
                        for (a; a < column; a++) {
                            if (r != row) {
                                $("#r-" + original_row + "-" + column + "").css("display", "");
                                $("#r-" + original_row + "-" + (Number(column) + 1) + "").css("display", "none");
                                $("#r-" + original_row + "-" + (Number(column) + 2) + "").css("display", "none");
                                $("#r-" + original_row + "-" + (Number(column) + 3) + "").css("display", "");
                            }
                        }
                        for (b; b < column; b++) {
                            $("#r-" + original_row + "-" + b + "").empty();
                            $("#r-" + original_row + "-" + b + "").append($("#r-" + original_row + "-" + b + "").attr("Datavalue"));
                        }
                    }
                    
                }, function () {
                    //layer.msg('取消', {
                    //    time: 20000, //20s后自动关闭
                    //    btn: ['明白了', '知道了']
                    //});
                });
            } else { layer.msg('无数据', { icon: 2, time: 2000 }); }
            break;
        default:
            //type 与 case 1 和 case 2 不同时执行的代码
    }

}


function deleteAll(tableid)
{
    var li = 0, deleteID = null, licount, rowid = [];
    licount = $("#cont tr").length;
    for (li; li < licount; li++) {
        if ($("#del-" + li).is(":checked")) {
            rowid.push("#r-" + li);
            deleteCount = deleteCount + 1;
            if (deleteID == null) { deleteID = "'" + $("#del-" + li).attr("datavalue") + "'"; }
            else { deleteID = deleteID + ",'" + $("#del-" + li).attr("datavalue") + "'"; }
        } else { continue; }
    }
    if (deleteID != null) {
    layer.confirm('您是否要删除？', {
        btn: ['是的', '算了'] //按钮
    }, function () {  
        var sqlstring = "delete from " + tableid + " where " + $("#checkall").attr("Dataid") + " in(" + deleteID + ");"
        if (execute(sqlstring)) {
            for (var i = 0; i < rowid.length; i++)
            {
                $(rowid[i]).remove();
            }
                rowid = [];
                var row_count = $("#cont tr").length;
                console.log(row_count);
                if (row_count == 0) {
                    curr_num = parseInt(curr_num) - 1 <= 0 ? 1 : parseInt(curr_num) - 1;
                    deleteCount = deleteCount + rowid.length;
                    var current = Math.ceil((parseInt(datacount) - parseInt(deleteCount)) / $("#select_row").val());
                    $.jqPaginator('.pagination', {
                        totalPages: parseInt(current),
                        visiblePages: parseInt($("#select_row").val()),
                        //currentPage: parseInt(curr_num) - 1 == 0 ? curr_num = 1 : parseInt(curr_num) - 1,
                        currentPage: curr_num,
                        onPageChange: function (num, type) {
                            curr_num = num;
                            get(_get_url, _Array_id, _container, _row, _column, _Array_title, _table, curr_num);
                        }
                    });
                }
            
        }
    } , function () {
            //layer.msg('取消', {
            //    time: 20000, //20s后自动关闭
            //    btn: ['明白了', '知道了']
            //});
        });
            
     } else { layer.msg('请先选择要删除的数据！', { icon: 2, time: 2000 }); };
}

function adduser(tableid) {
    $("#addbtn").attr("disabled", "disabled");
    $("#addbtn").attr('value', "loading");
    setTimeout(function () {
        $("#addbtn").attr('value', "添加");
        $("#addbtn").removeAttr("disabled");
    }, 2000);
    var d = new Date();
    var t = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();
    var value = "'" + uuid(8, 16) + "','" + $("#username").val() + "','" + $("#password").val() + "','" + $("#email").val() + "','" + t + "'";
    
    var sqlstring = "insert into " + tableid + " values(" + value + ");"
    execute(sqlstring)
    
}
// pagecount num当前页  curr_num全局变量 存储当前页    datacount纪录总数
//第一次加载分页
function page(page_url, get_url, Array_id, container, row, column, Array_title, table, func) {
    var tmp = Math.random().toString();
    var sql = "select count(*) from " + table;
    console.log(sql);
    $.ajax({
        type: 'POST',
        url: page_url + tmp,
        data: "sql=" + sql,
        dataType: 'text',
        cache: false,
        beforeSend: function () {
            dialogID = layer.load(2, { shade: [0.1, '#fff'] });
        },
        success: function (data, textStatus) {
            //layer.close(dialogID);
           
            datacount = parseInt(data) == 0 ? data = 1 : data;
            var select_row= parseInt($("#select_row").val()) ? parseInt($("#select_row").val()) : 10;
            var current = Math.ceil(parseInt(datacount) /select_row);
           
            $.jqPaginator('.pagination', {
                totalPages: parseInt(current),
                visiblePages: select_row,
                currentPage: 1,
                onPageChange: function (num, type) {
                    curr_num = num;  //(curr_num,num)当前页              
                    _page_url = page_url;//（_page_url,page_url)分页处理地址
                    _get_url = get_url;//(_get_url , get_url)获取数据地址
                    _Array_id = Array_id;//（_Array_id,Array_id）数据表字段id 
                    _container = container;//(_container,container) 容器id
                    _row = row;// (_row,row)行
                    _column = column;// (_column,column)列
                    _table = table;//(_table,table)修改的表名
                    _Array_title = Array_title;//(_Array_title,Array_title)表头标题
                    console.log(type + '---' + curr_num);
                    get(_get_url, _Array_id, _container, _row, _column, _Array_title, _table, curr_num, func);
                }
            });

        },
        error: function (xhr) {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                console.log(xhr);
                this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                return;
            }
            layer.close(dialogID);
            layer.msg('加载失败', { icon: 1, time: 2000 });
            return;
        },

    });
}

function ResetTable() {
    //initiate dataTables plugin
    //.wrap("<div class='dataTables_borderWrap' />")   //if you are applying horizontal scrolling (sScrollX)
    myTable = $('#dynamic-table').DataTable();
    //$('#dynamic-table').dataTable().fnDestroy();

        $.fn.dataTable.Buttons.defaults.dom.container.className = 'dt-buttons btn-overlap btn-group btn-overlap';
        new $.fn.dataTable.Buttons(myTable, {
            buttons: [
              {
                  "extend": "colvis",
                  "text": "<i class='fa fa-search bigger-110 blue'></i> <span class='hidden'>筛选列</span>",
                  "className": "btn btn-white btn-primary btn-bold",
                  columns: ':not(:first):not(:last)'
              },
              {
                  "extend": "copy",
                  "text": "<i class='fa fa-copy bigger-110 pink'></i> <span class='hidden'>复制到剪贴板</span>",
                  "className": "btn btn-white btn-primary btn-bold"
              },
              {
                  "extend": "csv",
                  "text": "<i class='fa fa-database bigger-110 orange'></i> <span class='hidden'>转换为CSV</span>",
                  "className": "btn btn-white btn-primary btn-bold"
              },
              {
                  "extend": "excel",
                  "text": "<i class='fa fa-file-excel-o bigger-110 green'></i> <span class='hidden'>转换为Excel</span>",
                  "className": "btn btn-white btn-primary btn-bold"
              },
              {
                  "extend": "pdf",
                  "text": "<i class='fa fa-file-pdf-o bigger-110 red'></i> <span class='hidden'>转换为PDF</span>",
                  "className": "btn btn-white btn-primary btn-bold"
              },
              {
                  "extend": "print",
                  "text": "<i class='fa fa-print bigger-110 grey'></i> <span class='hidden'>打印</span>",
                  "className": "btn btn-white btn-primary btn-bold",
                  autoPrint: false,
                  message: 'This print was produced using the Print button for DataTables'
              },
            ]
        });
        if ($('.tableTools-container').length > 0) { $('.tableTools-container').empty();}
        myTable.buttons().container().appendTo($('.tableTools-container'));
        $(".tableTools-container").prepend("<div class='dt-buttons btn-overlap btn-group'>"
        + "<button id='add' class='btn btn-white btn-primary btn-bold' title='添加' onclick='Addbtn();'><i class='fa fa-plus bigger-110'></i></button>"
        + "<button class='btn btn-white  btn-primary btn-bold'  data-rel='tooltip' data-original-title='删除' onclick='Delbtn();'><i class='fa fa-trash-o bigger-120 orange'></i></button>"
        + "<button class='btn btn-white  btn-primary btn-bold'  data-rel='tooltip' data-original-title='重载' onclick='Refreshbtn();'><i class='fa fa-refresh bigger-120 pink'></i></button></div>");



    //style the message box
    var defaultCopyAction = myTable.button(1).action();
    myTable.button(1).action(function (e, dt, button, config) {
        defaultCopyAction(e, dt, button, config);
        $('.dt-button-info').addClass('gritter-item-wrapper gritter-info gritter-center white');
    });


    var defaultColvisAction = myTable.button(0).action();
    myTable.button(0).action(function (e, dt, button, config) {

        defaultColvisAction(e, dt, button, config);


        if ($('.dt-button-collection > .dropdown-menu').length == 0) {
            $('.dt-button-collection')
            .wrapInner('<ul class="dropdown-menu dropdown-light dropdown-caret dropdown-caret" />')
            .find('a').attr('href', '#').wrap("<li />")
        }
        $('.dt-button-collection').appendTo('.tableTools-container .dt-buttons')
    });

    ////

    setTimeout(function () {
        $($('.tableTools-container')).find('a.dt-button').each(function () {
            var div = $(this).find(' > div').first();
            if (div.length == 1) div.tooltip({ container: 'body', title: div.parent().text() });
            else $(this).tooltip({ container: 'body', title: $(this).text() });
        });
    }, 500);





    myTable.on('select', function (e, dt, type, index) {
        if (type === 'row') {
            $(myTable.row(index).node()).find('input:checkbox').prop('checked', true);
        }
    });
    myTable.on('deselect', function (e, dt, type, index) {
        if (type === 'row') {
            $(myTable.row(index).node()).find('input:checkbox').prop('checked', false);
        }
    });




    /////////////////////////////////
    //table checkboxes
    $('th input[type=checkbox], td input[type=checkbox]').prop('checked', false);

    //select/deselect all rows according to table header checkbox
    $('#dynamic-table > thead > tr > th input[type=checkbox], #dynamic-table_wrapper input[type=checkbox]').eq(0).on('click', function () {
        var th_checked = this.checked;//checkbox inside "TH" table header

        $('#dynamic-table').find('tbody > tr').each(function () {
            var row = this;
            if (th_checked) myTable.row(row).select();
            else myTable.row(row).deselect();
        });
    });

    //select/deselect a row when the checkbox is checked/unchecked
    $('#dynamic-table').on('click', 'td input[type=checkbox]', function () {
        var row = $(this).closest('tr').get(0);
        if (this.checked) myTable.row(row).deselect();
        else myTable.row(row).select();
    });



    $(document).on('click', '#dynamic-table .dropdown-toggle', function (e) {
        e.stopImmediatePropagation();
        e.stopPropagation();
        e.preventDefault();
    });


    /*************悬浮提示****************/
    //add tooltip for small view action buttons in dropdown menu
    //$('[data-rel="tooltip"]').tooltip({ placement: tooltip_placement });
    $('[data-rel="tooltip"]').tooltip();

    //tooltip placement on right or left
    function tooltip_placement(context, source) {
        var $source = $(source);
        var $parent = $source.closest('table')
        var off1 = $parent.offset();
        var w1 = $parent.width();

        var off2 = $source.offset();
        //var w2 = $source.width();

        if (parseInt(off2.left) < parseInt(off1.left) + parseInt(w1 / 2)) return 'right';
        return 'left';
    }


    /***************/
    $('.show-details-btn').on('click', function (e) {
        e.preventDefault();
        $(this).closest('tr').next().toggleClass('open');
        $(this).find(ace.vars['.icon']).toggleClass('fa-angle-double-down').toggleClass('fa-angle-double-up');
    });
    /***************/

}
/**********************************************************************************************************************/


//刷新按钮
function Refreshbtn() {
    var Array_title = new Array("用户名", "密码", "邮箱", "注册时间", "处理");
    var Array_id = new Array("user_id", "user_name", "user_pwd", "user_email", "time");
    page("handler/PageHandler.ashx?t=", "handler/GetHandler.ashx?t=", Array_id, "main", '15', '6', Array_title, 'admin');
}
//添加按钮
function Addbtn() {
    var index = layer.open({
        type: 2,
        scrollbar: false,
        shade: [0.2, '#FFFFFF'],
        title: "添加用户",
        shadeClose: false,
        area: ['400px', '370px'],
        content: '/master/add-user.html',
    });
}
//删除按钮
function Delbtn() {
    deleteAll('admin');
}

function changerow(container, row, column) {
    if (localStorage.rowlength) { localStorage.rowlength = row; } else { $("#select_row").val("10"); localStorage.rowlength = "10"; }

        var Array_title = new Array("用户名", "密码", "邮箱", "注册时间", "处理");
        var Array_id = new Array("user_id", "user_name", "user_pwd", "user_email", "time");
        page("handler/PageHandler.ashx?t=", "handler/GetHandler.ashx?t=", Array_id, "main", row, '6', Array_title, 'admin');
    
}